﻿using Kimd.Common;
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Diagnostics;
using System.Drawing;
using System.Drawing.Text;
using System.IO;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;

namespace Kimd.Communication
{
    public partial class FormCommunication : Form
    {
        public event Action<SerializableDictionary<string, ICommunicationShow>> NotifyCommChanges;

        public SerializableDictionary<string, ICommunicationShow> _allComm;
        public FormCommunication(SerializableDictionary<string, ICommunicationShow> allComm)
        {
            InitializeComponent();
            _allComm = allComm;
        }

        private void FormCommunication_Load(object sender, EventArgs e)
        {
            PrivateFontCollection pfc = new PrivateFontCollection();
            //if (File.Exists("./fontawesome-webfont.ttf"))
            //{
                //pfc.AddFontFile("./fontawesome-webfont.ttf");
                //tSB_Modbus.Font = new Font(pfc.Families[0], 10);
                //tSB_SerialPort.Font = new Font(pfc.Families[0], 10);
                //tSB_TCPClient.Font = new Font(pfc.Families[0], 10);
                //tSB_TCPServer.Font = new Font(pfc.Families[0], 10);
                //tSB_Close.Font = new Font(pfc.Families[0], 10);
                //tSB_Open.Font = new Font(pfc.Families[0], 10);
                //TreeView_Comm.Font = new Font(pfc.Families[0], 10);
                //tSB_TCPServer.Text = "TCPServer";
                //tSB_TCPClient.Text = "TCPClient";
                //tSB_SerialPort.Text = "串口";
                //tSB_Modbus.Text = "Modbus";
                tSB_Close.Text = "关闭";
                tSB_Open.Text = "打开";
                this.TreeView_Comm.Nodes.Clear();
                TreeNode root = new TreeNode("Comms");
                root.ImageIndex = 0;
                root.SelectedImageIndex = 0;
                this.TreeView_Comm.Nodes.Add(root);
                if (_allComm != null)
                {
                    foreach (KeyValuePair<string, ICommunicationShow> commPair in _allComm)
                    {
                        string nodeStr = commPair.Value.GetTreeNodeShowStr();
                        TreeViewAddNodes(TreeView_Comm, nodeStr, commPair.Value);
                    }
                }
                TreeView_Comm.ExpandAll();
            //}
            timer_Update.Enabled = true;
        }

        private TreeNode TreeViewAddNodes(TreeView treeView, string nodeStr, ICommunicationShow communication)
        {
            TreeNode tn = new TreeNode(nodeStr);
            tn.Tag = communication;
            if (communication.IsOpenFlag)
            {
                tn.ImageIndex = 3;
                tn.SelectedImageIndex = 3;
                tn.SelectedImageIndex = 3;
                tn.ForeColor = Color.Green;
            }
            else
            {
                tn.ImageIndex = 4;
                tn.SelectedImageIndex = 4;
                tn.ForeColor = Color.Gray;
            }
            List<string> clients = communication.GetShowList();
            if (clients.Count > 0)
            {
                tn.Nodes.Clear();
                foreach (var item in clients)
                {
                    TreeNode tnChildren = new TreeNode(item);
                    tn.Nodes.Add(tnChildren);
                }
            }
            treeView.Nodes[0].Nodes.Add(tn);
            return tn;
        }

        private void TreeView_Comm_MouseClick(object sender, MouseEventArgs e)
        {
            if (e.Button == System.Windows.Forms.MouseButtons.Left)
            {
                Point ClickPoint = new Point(e.X, e.Y);
                TreeNode currentnode = TreeView_Comm.GetNodeAt(ClickPoint);
                if (currentnode != null)//判断你点的是不是一个节点
                {
                    TreeView_Comm.SelectedNode = currentnode;//选中这个节点
                    if (TreeView_Comm.SelectedNode.Tag != null)
                    {
                        ICommunicationShow comm = (ICommunicationShow)TreeView_Comm.SelectedNode.Tag;
                        if (comm != null)
                        {
                            tB_CommDescription.Text = comm.Name;
                            PropertyGrid_Config.SelectedObject = comm.GetConfig();
                            PropertyGrid_Config.Tag = false;
                        }
                    }
                }
            }
        }

        private void TreeView_Comm_MouseDown(object sender, MouseEventArgs e)
        {
            if (e.Button == System.Windows.Forms.MouseButtons.Right)
            {
                Point ClickPoint = new Point(e.X, e.Y);
                TreeNode currentnode = TreeView_Comm.GetNodeAt(ClickPoint);
                if (currentnode != null)//判断你点的是不是一个节点
                {
                    currentnode.ContextMenuStrip = cMS_Comm;
                    TreeView_Comm.SelectedNode = currentnode;//选中这个节点
                    ICommunicationShow comm = (ICommunicationShow)currentnode.Tag;
                    if (comm != null)
                    {
                        tB_CommDescription.Text = comm.Name;
                        PropertyGrid_Config.SelectedObject = comm.GetConfig();
                        PropertyGrid_Config.Tag = false;
                    }
                }
            }
        }



        private void PropertyGrid_Config_PropertyValueChanged(object s, PropertyValueChangedEventArgs e)
        {
            ICommunicationShow comm = (ICommunicationShow)TreeView_Comm.SelectedNode?.Tag;
            if (comm != null)
            {
                if (!string.IsNullOrEmpty(e.ChangedItem.Value.ToString()))
                {
                    object config = PropertyGrid_Config.SelectedObject;
                    comm.SetConfig(config);
                    comm.SetOpenOrClose(OpenOrClose.Close);
                }
            }
        }

        private void btn_RegisterComm_Click(object sender, EventArgs e)
        {
            if (TreeView_Comm.Nodes.Count == 0)
                return;
            if (PropertyGrid_Config.Tag == null)
            {
                MessageBox.Show("请选中需要注册的通讯设备", "通讯设备注册", MessageBoxButtons.OK, MessageBoxIcon.Information);
                return;
            }
            if (tB_CommDescription.Text == "")
            {
                MessageBox.Show("请输入注册的通讯设备名称", "通讯设备注册", MessageBoxButtons.OK, MessageBoxIcon.Information);
                return;
            }
            string newName = tB_CommDescription.Text;
            if (_allComm != null
                && TreeView_Comm.SelectedNode != null
                && TreeView_Comm.SelectedNode.Tag != null
                && PropertyGrid_Config.Tag != null
                && !((bool)PropertyGrid_Config.Tag))
            {
                if (_allComm.ContainsKey(((ICommunicationShow)TreeView_Comm.SelectedNode.Tag).Name))
                {
                    string oldName = ((ICommunicationShow)TreeView_Comm.SelectedNode.Tag).Name;
                    if (newName != oldName)
                    {
                        if (DialogResult.Yes == MessageBox.Show($"确定修改通讯设备名称为{newName}吗?", "修改名称", MessageBoxButtons.YesNo, MessageBoxIcon.Information))
                        {
                            _allComm.Remove(oldName);
                            ICommunicationShow communication = TreeView_Comm.SelectedNode.Tag as ICommunicationShow;
                            communication.Name = newName;
                            _allComm.Add(newName, communication);
                        }
                        else
                            return;
                    }
                }
                if (NotifyCommChanges != null)
                    NotifyCommChanges(_allComm);
                //MessageBox.Show("已注册该相机", "相机注册", MessageBoxButtons.OK, MessageBoxIcon.Information);
                MessageBox.Show("注册成功!", "通信设备", MessageBoxButtons.OK, MessageBoxIcon.Information);
                return;
            }
            else
            {
                if (PropertyGrid_Config.Tag != null
                    && ((bool)PropertyGrid_Config.Tag))
                {
                    if (_allComm == null)
                        _allComm = new SerializableDictionary<string, ICommunicationShow>();
                    if (_allComm.Keys.Contains(newName))
                    {
                        MessageBox.Show("当前设备名称已经存在", "通讯设备注册", MessageBoxButtons.OK, MessageBoxIcon.Information);
                        return;
                    }
                    object config = PropertyGrid_Config.SelectedObject;
                    if (config is TCPClientConfig)
                    {
                        TCPClient client = new TCPClient(newName);
                        client.SetConfig(config);
                        _allComm.Add(newName, client);
                        TreeNode tn = TreeViewAddNodes(TreeView_Comm, client.GetTreeNodeShowStr(), client);
                        TreeView_Comm.SelectedNode = tn;
                    }
                    if (config is TCPServerConfig)
                    {
                        TCPServer client = new TCPServer(newName);
                        client.SetConfig(config);
                        _allComm.Add(newName, client);
                        TreeNode tn = TreeViewAddNodes(TreeView_Comm, client.GetTreeNodeShowStr(), client);
                        TreeView_Comm.SelectedNode = tn;
                    }
                    if (config is ModbusConfig)
                    {
                        ModbusTcp client = new ModbusTcp(newName);
                        client.SetConfig(config);
                        _allComm.Add(newName, client);
                        TreeNode tn = TreeViewAddNodes(TreeView_Comm, client.GetTreeNodeShowStr(), client);
                        TreeView_Comm.SelectedNode = tn;
                    }
                    if (config is SerialPortConfig)
                    {
                        SerialPortHelper client = new SerialPortHelper(newName);
                        client.SetConfig(config);
                        _allComm.Add(newName, client);
                        TreeNode tn = TreeViewAddNodes(TreeView_Comm, client.GetTreeNodeShowStr(), client);
                        TreeView_Comm.SelectedNode = tn;
                    }
                    PropertyGrid_Config.Tag = false;
                    TreeView_Comm.ExpandAll();
                    if (NotifyCommChanges != null)
                        NotifyCommChanges(_allComm);
                    MessageBox.Show("注册成功!", "通信设备", MessageBoxButtons.OK, MessageBoxIcon.Information);
                }
            }
        }

        private void timer_Update_Tick(object sender, EventArgs e)
        {
            foreach (var item in TreeView_Comm.Nodes[0].Nodes)
            {
                if (item is TreeNode)
                {
                    TreeNode tn = item as TreeNode;
                    ICommunicationShow communication = tn.Tag as ICommunicationShow;
                    if (communication != null)
                    {
                        if (communication.IsOpenFlag)
                        {
                            tn.ImageIndex = 3;
                            tn.SelectedImageIndex = 3;
                            tn.ForeColor = Color.Green;
                        }
                        else
                        {
                            tn.ImageIndex = 4;
                            tn.SelectedImageIndex = 4;
                            tn.ForeColor = Color.Gray;
                        }
                        tn.Name = communication.GetTreeNodeShowStr();
                        tn.Text = communication.GetTreeNodeShowStr();
                        List<string> clients = communication.GetShowList();
                        if (communication.CommType == CommTypeEnum.TCPServer)
                        {
                            tn.Nodes.Clear();
                            if (clients.Count > 0)
                            {
                                foreach (var item1 in clients)
                                {
                                    TreeNode tnChildren = new TreeNode(item1);
                                    tn.Nodes.Add(tnChildren);
                                }
                            }
                        }
                    }
                }
            }
        }

        private void 删除ToolStripMenuItem_Click(object sender, EventArgs e)
        {
            if (TreeView_Comm.SelectedNode == null || TreeView_Comm.SelectedNode.Tag == null)
            {
                MessageBox.Show("请选中通讯设备节点!", "删除通讯设备", MessageBoxButtons.OK, MessageBoxIcon.Information);
                return;
            }
            ICommunicationShow communication = TreeView_Comm.SelectedNode.Tag as ICommunicationShow;
            if (communication != null)
            {
                communication.SetOpenOrClose(OpenOrClose.Close);
                _allComm.Remove(communication.Name);
                if (NotifyCommChanges != null)
                    NotifyCommChanges(_allComm);
                TreeView_Comm.Nodes.Remove(TreeView_Comm.SelectedNode);
            }
        }

        private void 调试ToolStripMenuItem_Click(object sender, EventArgs e)
        {
            if (TreeView_Comm.SelectedNode == null || TreeView_Comm.SelectedNode.Tag == null)
            {
                MessageBox.Show("请选中通讯设备节点!", "调试通讯设备", MessageBoxButtons.OK, MessageBoxIcon.Information);
                return;
            }
            ICommunicationShow communication = TreeView_Comm.SelectedNode.Tag as ICommunicationShow;
            if (communication != null)
            {
                Form form = communication.GetDebugForm();
                form.Show();
            }
        }

        private void tcpServerToolStripMenuItem_Click(object sender, EventArgs e)
        {
            if (sender is ToolStripButton)
            {
                ToolStripButton tsb = sender as ToolStripButton;
                if (tsb.Name.Equals(tSB_Close.Name) || tsb.Name.Equals(tSB_Open.Name))
                {
                    TreeNode node = TreeView_Comm.SelectedNode;
                    if (node != null && node.Tag != null)
                    {
                        ICommunicationShow communication = node.Tag as ICommunicationShow;
                        if (communication != null)
                        {
                            if (tsb.Name.Equals(tSB_Close.Name))
                            {
                                communication.SetOpenOrClose(OpenOrClose.Close);
                            }
                            if (tsb.Name.Equals(tSB_Open.Name))
                            {
                                communication.SetOpenOrClose(OpenOrClose.Open);
                            }
                        }
                    }
                }
            }
            if (sender is ToolStripMenuItem)
            {
                ToolStripMenuItem tsb = sender as ToolStripMenuItem;
                
                if (tsb.Name.Equals(modbusTcpToolStripMenuItem.Name))
                {
                    PropertyGrid_Config.SelectedObject = new ModbusConfig();
                }
                if (tsb.Name.Equals(tcpServerToolStripMenuItem.Name))
                {
                    PropertyGrid_Config.SelectedObject = new TCPServerConfig();
                }
                if (tsb.Name.Equals(tcpClientToolStripMenuItem.Name))
                {
                    PropertyGrid_Config.SelectedObject = new TCPClientConfig();
                }
                if (tsb.Name.Equals(串口ToolStripMenuItem.Name))
                {
                    PropertyGrid_Config.SelectedObject = new SerialPortConfig();
                }
                PropertyGrid_Config.Tag = true;
                TreeView_Comm.SelectedNode = null;
            }
        }
    }
}
